//
//  TransactionController.swift
//  SCA
//
//  Created by tjun on 2025/9/7.
//

import UIKit
 

class TransactionController: BaseController {
    
    private var scrollView: UIScrollView!
    private var contentView: UIView!
    
    private let coinTextField = LabeledTextField(tip: "       ")
    private let amountTextField = LabeledTextField(tip: "最低 1.00".localizedString)
    private let payeeTextField = LabeledTextField()
    private let passwordTextField = LabeledTextField()

    private let otpTextField = LabeledTextField(tip: "请输入绑定号2FA验证码".localizedString)
    private let confirmButton = MainButton(type: .system, title: "确认".localizedString, font: UIFontMake(16), textColor: .white)
    
    private var maxAmount: Float = Float.greatestFiniteMagnitude
    
    private let model: WalletCoinModel
    
    init(model: WalletCoinModel) {
        self.model = model
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationBar.title = "转账".localizedString
        setupUI()
    }
    
    private func setupUI() {
        
        scrollView = UIScrollView(frame: CGRect(x: 0, y: navBarHeight, width: view.width, height: screenHeight - navBarHeight)).addTo(view)
        scrollView.keyboardDismissMode = .onDrag
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.alwaysBounceVertical = true
        scrollView.contentInsetAdjustmentBehavior = .never
        
        let contentSize = CGSize(width: scrollView.width, height: scrollView.height)
        
        scrollView.contentSize = contentSize
        
        contentView = UIView().addTo(scrollView)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.size.equalTo(contentSize)
        }
 
        coinTextField.titleAttributedText = "转出代币*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        coinTextField.isUserInteractionEnabled = false
        contentView.addSubview(coinTextField)
        coinTextField.textField.keyboardType = .asciiCapable
        coinTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        coinTextField.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.left.right.equalToSuperview().inset(AppStyle.margin.left)
        }
        
        amountTextField.titleAttributedText = "数量*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        contentView.addSubview(amountTextField)
        amountTextField.textField.keyboardType = .decimalPad
        amountTextField.delegate = self
        amountTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        amountTextField.snp.makeConstraints { make in
            make.top.equalTo(coinTextField.snp.bottom).offset(10)
            make.left.right.equalTo(coinTextField)
        }
        
        payeeTextField.titleAttributedText = "收款人*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        contentView.addSubview(payeeTextField)
        payeeTextField.textField.keyboardType = .asciiCapable
        payeeTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        payeeTextField.snp.makeConstraints { make in
            make.top.equalTo(amountTextField.snp.bottom).offset(10)
            make.left.right.equalTo(coinTextField)
        }
        
        passwordTextField.titleAttributedText = "二级安全密码*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        contentView.addSubview(passwordTextField)
        passwordTextField.textField.keyboardType = .asciiCapable
        passwordTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        passwordTextField.snp.makeConstraints { make in
            make.top.equalTo(payeeTextField.snp.bottom).offset(10)
            make.left.right.equalTo(coinTextField)
        }
 
        otpTextField.titleAttributedText = "2FA OTP*".attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        contentView.addSubview(otpTextField)
        otpTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        otpTextField.snp.makeConstraints { make in
            make.top.equalTo(passwordTextField.snp.bottom).offset(10)
            make.left.right.equalTo(coinTextField)
        }
        
        confirmButton.addTo(contentView)
        confirmButton.isEnabled = false
        confirmButton.addTarget(self, action: #selector(confirmButtonTapped), for: .touchUpInside)
        confirmButton.snp.makeConstraints { make in
            make.left.right.equalTo(coinTextField)
            make.height.equalTo(AppStyle.size.buttonHeight.scaled)
            make.top.equalTo(otpTextField.snp.bottom).offset(50)
        }
        
        coinTextField.textField.text = model.coinName
        coinTextField.tipLabel.text = String(format: "余额: %@; 可用: %@".localizedString, model.balance, model.useable)
        let maxAmountString: NSString = (model.useable.replacingOccurrences(of: ",", with: "") as NSString)
        maxAmount = maxAmountString.floatValue

    }

    @objc func textFieldDidChange(_ sender: UITextField) {
        
        if let coin = coinTextField.textField.text,
           let amount = amountTextField.textField.text,
           let payee = payeeTextField.textField.text,
           let password = passwordTextField.textField.text,
           let otp = otpTextField.textField.text,
           coin.count > 0,
           (Float(amount) ?? 0) > 0,
           isValidUsername(payee),
           password.count >= 6,
           otp.count > 0 {
            confirmButton.isEnabled = true
        } else {
            confirmButton.isEnabled = false
        }
    }
 
    @objc func confirmButtonTapped() {
        guard let coin = coinTextField.textField.text,
           let amount = amountTextField.textField.text,
           let payee = payeeTextField.textField.text,
           let password = passwordTextField.textField.text,
           let otp = otpTextField.textField.text else {
            return
        }
        
        HUD.showLoadingInView(self.view)
        WalletService.transactionCheckUsername(coinName: coin, username: payee) { able in
            if able {
                WalletService.transaction(coinName: self.model.coinName.lowercased(), amount: amount, pinCcode: password, username: payee, otp: otp) {transactionAmount, error in
                    HUD.hideHUD(for: self.view)
                    if error == nil, let transaction_amount = transactionAmount {
                        let transactionSuccessController = TransactionSuccessController(text: String(format:  "转账成功! 您已成功转了\n %@ %@ 到 %@", transaction_amount, coin, payee))
                        self.navigationController?.pushViewController(transactionSuccessController, animated: true)
                        self.navigationController?.viewControllers = self.removeNavChildViewControllers(["TransactionController"])
                        NotificationCenter.default.post(name: NotificationName.transactionSuccess, object: nil)
                    } else {
                        HUD.showErrorMessage(error)
                    }
                }
            } else {
                HUD.showMessage("收款人错误".localizedString)
            }
        }
        
    }
 
}

 
extension TransactionController: LabeledTextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.isEmpty { return true } // 允许删除

        let allowedCharacters = CharacterSet(charactersIn: "0123456789.")
        if string.rangeOfCharacter(from: allowedCharacters.inverted) != nil {
            return false
        }

        guard let oldText = textField.text as NSString? else { return true }
        let newText = oldText.replacingCharacters(in: range, with: string)

        // 第一位不能是小数点
        if newText.count == 1, newText == "." {
            return false
        }

        // 第一位不能是 0，除非是 "0."
        if newText.count == 1, newText == "0" {
            return false
        }
        if newText.count >= 2, newText.hasPrefix("0"), !newText.hasPrefix("0.") {
            return false
        }

        // 小数点只能有一个
        if newText.filter({ $0 == "." }).count > 1 {
            return false
        }

        // 小数点后最多 3 位（纯字符串判断，避免 Float 丢精度问题）
        if let dotIndex = newText.firstIndex(of: ".") {
            let decimalPart = newText[newText.index(after: dotIndex)...]
            if decimalPart.count > 2 {
                return false
            }
        }

        // 数值范围检查
        if let value = Float(newText) {
            if value < 1 { return false }
            if value > maxAmount {
                DispatchQueue.main.async {
                    textField.text = "\(self.maxAmount)"
                }
                return false
            }
        }

        return true
    }
}

